<template>
  <!-- 章节列表 -->
  <div class="chapter">
    <tableComponents :isHavePagination="false" :isShow="false" :isHaveExport="false" @toAdd="editChapter(true)">
      <template v-slot:table>
        <el-table ref="multipleTable" :data="list" v-loading="loading" stripe header-row-class-name="head_color"
          tooltip-effect="dark" style="width: 99.9%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" class="tc" width="35"></el-table-column>

          <el-table-column label="排序" sortable :sort-method="sorta" align="center" width="80">
            <template slot-scope="scope">
              <div>
                <el-input @change="sortNew(scope.$index,scope.row)" v-model.number="scope.row.sort" autocomplete="off"
                  size="small"></el-input>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="标题" min-width="80">
            <template slot-scope="scope">{{ scope.row.title }}</template>
          </el-table-column>

          <el-table-column label="内容地址" min-width="80">
            <template slot-scope="scope">{{ scope.row.content }}</template>
          </el-table-column>

          <el-table-column prop="name" label="是否免费" align="center" min-width="80">
            <template slot-scope="scope">
              <el-switch class="zdySwith" :width="82" v-model="scope.row.is_free" active-color="#1aad19" inactive-color="#ffffff"
                active-text="收费" inactive-text="免费" active-value="1" inactive-value="0" @change="getFreeShow($event,scope.row)"></el-switch>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="是否目录加粗" align="center" min-width="80">
            <template slot-scope="scope">
              <el-switch class="zdySwith" :width="82" v-model="scope.row.is_bold" active-color="#1aad19" inactive-color="#ffffff"
                active-text="开启" inactive-text="关闭" active-value="1" inactive-value="0" @change="getBoldShow($event,scope.row)"></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" min-width="120">
            <template slot-scope="scope">
              <el-button :loading="$store.state.isLoading" size="mini" type="primary" @click="editChapter(false,scope.row)">编辑</el-button>
              <el-button :loading="$store.state.isLoading" size="mini" @click="deleteChapter(scope.$index, scope.row.id)"
                type="danger">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template v-slot:footerLeft>
        <a class="aBtn aBtn_1 aBtn_lan2" @click="deleteLises">删除</a>
      </template>
    </tableComponents>

    <el-dialog :close-on-click-modal="false" class="tl size_13" @close="class_show = false" title="编辑章节"
      :append-to-body="true" :visible.sync="chapter_show" width="800px">

      <el-form label-width="120px" :model="chapter" :rules="rules" ref="formLabel">

        <el-form-item label="标题：" prop="title">
          <el-col :span="12">
            <el-input type="text" clearable placeholder="请输入" v-model="chapter.title" autocomplete="off"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="小说文本地址：" prop="content">
          <el-col :span="12">
            <el-input type="text" disabled clearable placeholder="请上传txt格式文件" v-model="chapter.content" autocomplete="off"></el-input>
          </el-col>
          <el-col :span="4" :offset="1">
            <!-- :on-success="up_loader" -->
            <el-upload action="/api/common/upload/index/" ref="upload" accept=".txt" :auto-upload="true"
              :default-file-list="this.fileList" :show-file-list="false" :http-request="uploadSectionFile">
              <el-button type="primary">上传</el-button>
            </el-upload>
          </el-col>
        </el-form-item>

        <el-form-item label="是否付费：" prop="is_free">
          <el-col :span="12">
            <el-switch v-model="chapter.is_free" active-color="#13ce66" inactive-color="#999999" hone_switch :width="70"
              active-value="1" inactive-value="0"></el-switch>
          </el-col>
        </el-form-item>

        <el-form-item label="是否目录加粗：" prop="is_bold">
          <el-col :span="12">
            <el-switch v-model="chapter.is_bold" active-color="#13ce66" inactive-color="#999999" hone_switch :width="70"
              active-value="1" inactive-value="0"></el-switch>
          </el-col>
        </el-form-item>

        <el-form-item>
          <el-button :loading="$store.state.isLoading" @click="chapter_show = false">取 消</el-button>
          <el-button :loading="$store.state.isLoading" type="primary" @click="save('formLabel')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import axios from "axios";
  export default {
    data() {
      return {
        list: [],
        loading: false,
        multipleSelection: [],
        chapter_show: false,
        chapter: {},
        rules: {
          title: [{
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          }]
        },
        fileList: [],
        textData: ""
      }
    },
    created() {
      this.getChapter();
    },
    methods: {
      sorta(a, b) {
        return b - a;
      },
      sortNew(index, row) {
        this.$api.getNovel.editChapter(row).then(res => {
          if (res.data.code == 200) {
            this.getChapter();
          }
        });
      },
      getChapter() {
        //获取章节列表
        this.$api.getNovel.getChapter({
          id: this.$route.query.id
        }).then(res => {
          if (res.data.code == 200) {
            this.list = res.data.result;
          }
        })
      },
      handleSelectionChange(val) {
        //多选删除
        this.multipleSelection = val;
      },
      editChapter(bool, row) {
        //编辑添加章节
        this.fileList = [];
        if (bool) {
          this.chapter = {
            title: "",
            content: "",
            is_free: "0",
            is_bold: "0"
          };
        } else {
          this.chapter = row;
        }
        this.chapter_show = true;
      },
      save(formName) {
        //保存编辑
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.chapter.id) {
              //编辑
              this.$api.getNovel.editChapter(this.chapter).then(res => {
                if (res.data.code == 200) {
                  this.$message.success("修改成功");
                  this.chapter_show = false;
                  this.getChapter();
                } else {
                  this.$message.error(res.data.result);
                }
              })
            } else {
              //添加
              var params = this.chapter;
              params.id = this.$route.query.id;
              this.$api.getNovel.addChapter(this.chapter).then(res => {
                if (res.data.code == 200) {
                  this.$message.success("添加成功");
                  this.chapter_show = false;
                  this.getChapter();
                } else {
                  this.$message.error(res.data.result);
                }
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      getFreeShow(index, row) {
        //是否免费
        row.is_free = index;
        this.$api.getNovel.editChapter(row).then(res => {
          if (res.data.code == 200) {
            return;
          }
        })
      },
      getBoldShow(index, row) {
        //是否目录加粗
        row.is_bold = index;
        this.$api.getNovel.editChapter(row).then(res => {
          if (res.data.code == 200) {
            return;
          }
        })
      },
      deleteChapter(index, id) {
        //单条数据删除
        this.$swal({
          title: "您确定要删除这些信息吗",
          text: "删除后将无法恢复，请谨慎操作！",
          type: "warning",
          showCancelButton: true,
          confirmButtonColor: "#DD6B55",
          confirmButtonText: "是的，我要删除",
          cancelButtonText: "容我三思",
        }).then((willDelete) => {
          if (willDelete.value) {
            this.$api.getNovel.delChapter({
              id_str: id
            }).then((res) => {
              if (res.data.code == 200) {
                this.$swal("删除成功！", "您已经删除了这条信息。", "success");
                this.getChapter();
              } else {
                this.$swal("删除失败！", res.data.result, "error");
                this.getChapter();
              }
            });
          }
        });
      },
      deleteLises() {
        //批量删除
        var str = "";
        if (this.multipleSelection.length <= 0) {
          this.$message.error("未选择批量删除");
        } else {
          for (var i in this.multipleSelection) {
            str += this.multipleSelection[i].id + "@";
          }
          str = str.slice(0, -1);
          this.$swal({
            title: "您确定要删除这些信息吗",
            text: "删除后将无法恢复，请谨慎操作！",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "是的，我要删除",
            cancelButtonText: "容我三思",
          }).then((willDelete) => {
            if (willDelete.value) {
              var data = {
                id_str: str
              };
              this.$api.getNovel.delChapter(data).then((res) => {
                if (res.data.code == 200) {
                  this.$swal("删除成功！", "您已经删除了这些信息。", "success");
                  this.getChapter();
                } else {
                  this.$swal("删除失败！", "出错啦！", "error");
                }
              });
            }
          });
        }
      },
      up_loader(response) {
        //上传文件成功
        // console.log("iiiiiiiiiiiiiiiiiiiiiL:",response)
        this.loading = true;
        if (response.code == 200) {
          this.loading = false;
          this.chapter.content = response.result;
        } else {
          this.loading = false;
          this.fileList = [];
          this.$fnc.alertError(response.code_desc, response.result);
        }
      },
      uploadSectionFile(param) {
        var fileObj = param.file;
        // FormData 对象
        var form = new FormData();
        // 文件对象
        form.append('file', fileObj);
        axios({
          method: 'post',
          url: '/api/common/upload/index/',
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          data: form
        }).then(res => {
          this.loading = true;
          if(res.data.code == 200){
            this.loading = false;
            this.chapter.content = res.data.result;
          } else {
          this.loading = false;
          this.fileList = [];
          this.$fnc.alertError(response.code_desc, response.result);
        }
        });
      }
    },
  }
</script>

<style>
</style>
